package xman.mstruts.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import com.opensymphony.xwork2.Action;

public class AbstractAction implements Action, ServletRequestAware, ServletResponseAware {
    public static final String SUCCESS = "success";
    
    public static final String ERROR = "error";
    
    public static final String INPUT = "input";
    
    protected String callback;
    
    protected HttpServletRequest req;
    
    protected HttpServletResponse rsp;
    
    private static Logger logger = Logger.getLogger(AbstractAction.class);
    
    protected void output(String data, String callback) {
        if (StringUtils.isNotEmpty(callback)) {
            data = callback + "(" + data + ")";
        }
        outputAJAXStream(data, "utf-8");
    }
    
    private void outputAJAXStream(String data, String charset) {
        rsp.setHeader("P3P", "CP=CAO PSA OUR");
        PrintWriter writer = null;
        try {
            writer = rsp.getWriter();
            writer.write(data);
        } catch (Exception e) {
            logger.error(e);
        } finally {
            IOUtils.closeQuietly(writer);
        }
    }
    
    protected void writeFile(File desFile) {
        BufferedInputStream inputStream = null;
        FileOutputStream outputStream = null;
        try {
            inputStream = new BufferedInputStream(req.getInputStream());
            outputStream = new FileOutputStream(desFile);
            int v = 0;
            byte[] bytes = new byte[1024];
            while ((v = inputStream.read(bytes)) > 0) {
                outputStream.write(bytes, 0, v);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
    
    public static void setGZipHeaderVary(HttpServletResponse rsp) {
        rsp.setHeader("Vary", "Accept-Encoding");
    }
    
    public static void setNoCacheHeader(HttpServletResponse rsp) {
        rsp.setHeader("Pragma", "No-Cache");
        rsp.setHeader("Cache-Control", "No-Cache;No-Store");
        rsp.setDateHeader("Expires", 0);
    }
    
    /*-
     * HttpServletRequest.setCharacterEncoding(); 
     * 仅仅只适用于设置post提交的request body的解码而不是设置get方法提交的queryString的解码。POST提交的数据是作为request body的一部分
     * 注意：若没有设定characterEncoding，则使用ISO-8859-1来解码用户输入的表单，而不是使用系统默认的编码
     * 
     * HttpServletResponse.setContentType();
     * 告诉浏览器网页中数据是什么编码；表单提交时，根据ContentType指定的charset对表单中的数据编码，然后发送给服务器
     * 
     * HttpServletRequest.getParameter("name");
     * 返回的字符串为：queryString（包括get和post），其值经过Servlet服务器URLDecode过的，默认编码来源于应用服务器中的配置，比如tomcat中server.xml的URIEncoding,默认使用iso-8859-1。
     *
     * HttpServletRequest.getPathInfo();
     * 返回的字符串为：pathinfo；由Servlet服务器解码(decode)过的。默认编码同上，tomcat中可设置useBodyEncodingForURI。
     * 
     * HttpServletRequest.getRequestURI();
     * 返回的字符串为：contextPath/servletPath/pathinfo；注意是浏览器提交过来的原始数据，未被Servlet服务器URLDecode过
     */
    public static void setRspContentType(HttpServletResponse rsp, String charset) {
        rsp.setCharacterEncoding(charset);
        // 字节流方式 —— 输出到response.getOutputStream()。一般用来输出二进制内容，例如图片
        // 字符流方式 —— 输出到response.getWriter()。用来输出文本类型的内容，如HTML和纯文本
        // response.getWriter()通过content type中指定的字符编码来决定如何将字符流转换成字节流
        rsp.setContentType("text/html;charset=" + charset);

    }
    
    public String getCallback() {
        return callback;
    }
    
    public void setCallback(String callback) {
        this.callback = callback;
    }
    
    @Override
    public void setServletResponse(HttpServletResponse rsp) {
        this.rsp = rsp;
    }
    
    @Override
    public void setServletRequest(HttpServletRequest req) {
        this.req = req;
    }
    
    @Override
    public String execute() throws Exception {
        return null;
    }
}
